import { DeleteOutlined, PlusOutlined } from '@vicons/antd';
import { isArray, isFunction } from 'lodash-es';
import type { Ref } from 'vue';

import type { ActionButton } from '@/components/table/src/types/action-button';
import type { CrudContext } from '@/components/crud/src/context/use-crud-context';

export function buildToolbarActionButtons(context: CrudContext) {
  const createButton = shallowReactive<ActionButton>({
    name: '新增',
    icon: PlusOutlined,
    key: 'create',
    type: 'primary',
    disabled: false,
    display: true,
    loading: false,
    onClick: async () => {
      context.handleCreate();
    },
  });

  const batchDeleteButton = shallowReactive<ActionButton>({
    name: '批量删除',
    icon: DeleteOutlined,
    key: 'batchDelete',
    type: 'error',
    secondary: true,
    disabled: true,
    display: true,
    loading: false,
    batch: true,
    onClick: async () => {
      context.handleBatchDelete();
    },
  });

  if (isArray(context.toolbarActionButtons)) {
    context.toolbarActionButtons.filter(button => button.display ?? true);
    return [createButton, batchDeleteButton, ...context.toolbarActionButtons];
  }

  if (isFunction(context.toolbarActionButtons)) {
    const buttons = context.toolbarActionButtons.call(undefined, {
      createButton,
      batchDeleteButton,
    });
    buttons.filter(button => button.display ?? true);
    return buttons;
  }

  return [createButton, batchDeleteButton];
}

export function useToolBarActionButtons(context: CrudContext, selectedValues: Ref<Array<string | number>>) {
  return computed(() => {
    return buildToolbarActionButtons(context).map(button => {
      const disabled = selectedValues.value.length <= 0 && button.batch;

      return {
        ...button,
        disabled,
      };
    });
  });
}
